package com.zpark.sports.controller.exception;

import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
//@RestController
public class CustomExceptionHandlerController extends AbstractErrorController {
    //定义错误路径
    private final static String ERROR_PATH="/error";
    //添加构造器
    public CustomExceptionHandlerController(ErrorAttributes errorAttributes) {
        //调用父类构造器，创造父类对象
        super(errorAttributes);
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @RequestMapping(ERROR_PATH)
    public ModelAndView customHandler(HttpServletRequest request){
        Map<String,Object> map=getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE));
        //创建视图解析对象
        ModelAndView mv=new ModelAndView();
        //设置视图解析器
        mv.setViewName("404");
        //定义返回的数据类型
        Map<String,Object> result=new HashMap<>();
        //封装错误信息数据
        result.put("code",map.get("status"));
        result.put("msg",map.get("error"));
        //绑定数据
        mv.addObject("res",result);
        return mv;
    }
}
//    @RequestMapping(ERROR_PATH)
//    public Map<String,Object> customHandler(HttpServletRequest request){
//        Map<String,Object> map=getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE));
//
//        //定义返回的数据类型
//        Map<String,Object> result=new HashMap<>();
//        //封装错误信息数据
//        result.put("code",map.get("status"));
//        result.put("mag",map.get("error"));
//
//
//        return result;
//    }
//